package android

import (
	"encoding/base64"
	"github.com/beevik/etree"
	"log"
	"regexp"
	"strconv"
)

var (
	SelectEles       []*etree.Element
	CheckResourceIds = make(map[string]func(ele *etree.Element)) // 需要检测的节点resources_id 及其 对应的处理方法
)

// AllEle 调用该函数的childELes为doc的根节点, key和value为需要匹配的节点
func AllEle(childEles []*etree.Element, key, value string) {
	for _, childEle := range childEles {
		id := childEle.SelectAttr(key)
		if id != nil {
			if f, ok := CheckResourceIds[id.Value]; ok {
				f(childEle)
				childEle.RemoveAttr("resource-id")
			}
			if id.Value == value {
				SelectEles = append(SelectEles, childEle)
			}
		}
		AllEle(childEle.ChildElements(), key, value)
	}
}

// GetEleBounds 获取ele坐标
func GetEleBounds(ele *etree.Element) (res []int) {
	if bounds := ele.SelectAttr("bounds"); bounds != nil {
		re := regexp.MustCompile(`\d+`)
		matches := re.FindAllString(bounds.Value, -1)
		if len(matches) != 4 {
			return
		}
		res = append(res, (sToi(matches[0])+sToi(matches[2]))/2, (sToi(matches[1])+sToi(matches[3]))/2,
			sToi(matches[0]), sToi(matches[1]), sToi(matches[2]), sToi(matches[3]))
	}
	return
}

func ClickEle(ele *etree.Element) {
	if ele == nil {
		log.Println("nil ele please check")
		return
	}
	log.Println(GetEleBounds(ele))
}

func ClearSelectEles() {
	SelectEles = []*etree.Element{}
}

func sToi(s string) int {
	i, err := strconv.Atoi(s)
	if err != nil {
		return 0
	}
	return i
}

func Bs64(s string) string {
	return base64.StdEncoding.EncodeToString([]byte(s))
}
